<?php

namespace App\Biz;

use App\Events\VisitorReservesEvent;
use App\Exceptions\TokenExpiredException;
use App\Models\BaseMode;
use App\Models\Config;
use App\Models\Reserves;
use App\Models\Visitor;
use Carbon\Carbon;
use Exception;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class VisitorReservesBiz extends BaseBiz
{
    protected ConfigBiz             $configBiz;
    protected HttpBiz               $httpBiz;
    protected VisitorReservesLogBiz $visitorReservesLogBiz;

    /**
     * @param Reserves $reserves
     * @param HttpBiz $httpBiz
     * @param VisitorReservesLogBiz $visitorReservesLogBiz
     */
    public function __construct(Reserves $reserves, HttpBiz $httpBiz, VisitorReservesLogBiz $visitorReservesLogBiz)
    {
        $this->model                 = $reserves;
        $this->configBiz             = app(ConfigBiz::class);
        $this->httpBiz               = $httpBiz;
        $this->visitorReservesLogBiz = $visitorReservesLogBiz;
    }

    /**
     * 预约所有访客
     * @return void
     * @throws Exception
     */
    public function visitorReserves(): void
    {
        //获取访客预约表信息
        $reservesList = $this->model->with([
            'intervieweeInformation',
            'visitor',
            'visitor.visitorReservesLog' => function (HasMany $query) {
                $query->whereBetween('created_at', [Carbon::today()->startOfDay(),Carbon::today()->endOfDay()]);
            }
        ])
            ->where('status', BaseMode::STATUS_OPEN)
            ->get();

        if ($reservesList->isNotEmpty()) {
            foreach ($reservesList as $reserves) {
                if ($reserves->visitor->isNotEmpty() && $reserves->intervieweeInformation) {
                    //循环获取访客预约表中访客信息
                    foreach ($reserves->visitor as $visitor) {
                        if ($visitor->visitorReservesLog->isEmpty() && $visitor->url){
                            //访客预约
                            $this->submitVisitorReserves($this->configBiz->getConfig(), $reserves, $visitor);
                        }
                    }
                }
            }
        }
    }

    /**
     * 提交访客预约
     * @param Config $config
     * @param Reserves $reserves
     * @param Visitor $visitor
     * @return bool|false
     */
    public function submitVisitorReserves(Config $config, Reserves $reserves, Visitor $visitor): bool
    {
        try {

            $this->httpBiz->submitVisitorReserves([
                "appId"            => $config->appId,
                "authorId"         => $config->authorId,
                "captcha"          => "",
                "deviceGroups"     => $reserves->device_groups,
                "interviewee"      => $reserves->intervieweeInformation->name,
                "intervieweePhone" => $reserves->intervieweeInformation->phone,
                "openId"           => $visitor->openId,
                "passType"         => 1,
                "peers"            => [],
                "photos"           => [
                    [
                        "id"  => $visitor->url,
                        "url" => "http://10.131.9.133:30089/{$visitor->url}"
                    ]
                ],
                "reason"           => $reserves->reason,
                "source"           => $reserves->source,
                "startTime"        => $reserves->start_time_u_t_c,
                "endTime"          => $reserves->end_time_u_t_c,
                "telephone"        => $visitor->telephone,
                "visitorName"      => $visitor->visitorName,
            ]);

        } catch (\Exception $e) {
            Log::error("{$visitor->visitorName}访客预约失败 {$e->getMessage()}");

            dump($e->getMessage());
            return false;
        }

        event(new VisitorReservesEvent($config,$reserves,$visitor));
        Log::info("{$visitor->visitorName}访客预约成功");
        return true;
    }

    /**
     * 人脸图片上传
     * @param UploadedFile $file
     * @return Collection
     * @throws TokenExpiredException
     */
    public function imageUpload(UploadedFile $file): Collection
    {
        return $this->httpBiz->imageUpload($file);
    }
}
